package com.yupi.picturebackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.picturebackend.exception.BusinessException;
import com.yupi.picturebackend.exception.ErrorCode;
import com.yupi.picturebackend.model.entity.Picture;
import com.yupi.picturebackend.model.entity.PictureFavour;
import com.yupi.picturebackend.model.entity.User;
import com.yupi.picturebackend.service.PictureFavourService;
import com.yupi.picturebackend.mapper.PictureFavourMapper;
import com.yupi.picturebackend.service.PictureService;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
* @author 伍立权
* @description 针对表【picture_favour(图片收藏)】的数据库操作Service实现
* @createDate 2025-04-20 17:06:01
*/
@Service
public class PictureFavourServiceImpl extends ServiceImpl<PictureFavourMapper, PictureFavour>
    implements PictureFavourService{

    @Resource
    private PictureService pictureService;

    @Override
    public int doPictureFavour(long pictureId, User loginUser) {
        // 判断是否存在
        Picture picture = pictureService.getById(pictureId);
        if (picture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已图片收藏
        long userId = loginUser.getId();
        // 每个用户串行图片收藏
        // 锁必须要包裹住事务方法
        PictureFavourService pictureFavourService = (PictureFavourService) AopContext.currentProxy();
        synchronized (String.valueOf(userId).intern()) {
            return pictureFavourService.doPictureFavourInner(userId, pictureId);
        }
    }

    /**
     * 分页获取用户收藏的图片
     * @param page
     * @param queryWrapper
     * @param favourUserId
     * @return
     */
    @Override
    public Page<Picture> listFavourPictureByPage(IPage<Picture> page, Wrapper<Picture> queryWrapper,
                                                 long favourUserId) {
        if (favourUserId <= 0) {
            return new Page<>();
        }
        return baseMapper.listFavourPictureByPage(page, queryWrapper, favourUserId);
    }

    /**
     * 封装了事务的方法
     *
     * @param userId
     * @param pictureId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int doPictureFavourInner(long userId, long pictureId) {
        PictureFavour pictureFavour = new PictureFavour();
        pictureFavour.setUserId(userId);
        pictureFavour.setPictureId(pictureId);
        QueryWrapper<PictureFavour> postFavourQueryWrapper = new QueryWrapper<>(pictureFavour);
        PictureFavour oldPostFavour = this.getOne(postFavourQueryWrapper);
        boolean result;
        // 已收藏
        if (oldPostFavour != null) {
            result = this.remove(postFavourQueryWrapper);
            if (result) {
                // 图片收藏数 - 1
                result = pictureService.update()
                        .eq("id", pictureId)
                        .gt("favourNum", 0)
                        .setSql("favourNum = favourNum - 1")
                        .update();
                return result ? -1 : 0;
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        } else {
            // 未图片收藏
            result = this.save(pictureFavour);
            if (result) {
                // 图片收藏数 + 1
                result = pictureService.update()
                        .eq("id", pictureId)
                        .setSql("favourNum = favourNum + 1")
                        .update();
                return result ? 1 : 0;
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
    }
}




